package com.teradata.iodata.service;

import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataCRUDHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataGetHandler;
import org.apache.olingo.commons.api.ex.ODataException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

@WebServlet(name = "Tutorial", urlPatterns = "/Tutorial.svc/*")
public class OdataServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String PUNIT_NAME = "Tutorial";

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Autowired
    private DataSource dataSource;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            Map<String, String[]> parameterMap = req.getParameterMap();

            for (String paramKey : parameterMap.keySet()) {
                System.out.println("Elem:" + paramKey + " EValue:" + Arrays.toString(parameterMap.get(paramKey)));
            }

            System.out.println("getPathInfo:" + req.getPathInfo());
            System.out.println("getPathTranslated:" + req.getPathTranslated());
            System.out.println("getContextPath:" + req.getContextPath());
            System.out.println("getServletPath:" + req.getServletPath());
            Enumeration<Locale> locales = req.getLocales();
            while (locales.hasMoreElements()) {
                System.out.println(locales.nextElement());
            }

            System.out.println("getLocales:" + locales);

            JPAEdmProvider metadataProvider = new JPAEdmProvider(PUNIT_NAME, this.entityManagerFactory, null, null);
            JPAODataGetHandler jpaODataGetHandler = new JPAODataGetHandler(PUNIT_NAME, dataSource, entityManagerFactory, metadataProvider);
            //JPAODataGetHandler jpaODataGetHandler = new JPAODataGetHandler(PUNIT_NAME, dataSource, entityManagerFactory);
            jpaODataGetHandler.process(req, resp);
            //JPAODataCRUDHandler jpaoDataCRUDHandler = new JPAODataCRUDHandler(PUNIT_NAME, dataSource, entityManagerFactory, metadataProvider);

            //jpaoDataCRUDHandler.process(req, resp);

        } catch (RuntimeException | ODataException e) {
            throw new ServletException(e);
        }
    }
}
